package com.ctgu.server.utils;


import com.alibaba.fastjson.JSONObject;
import com.ctgu.server.components.exceptions.HttpClientException;

import java.util.HashMap;
import java.util.Map;


public class WeiXinUtil {
    //微信小程序APP_ID
    private static final String APP_ID="wx7d3c5abc1ae483eb";
    private static final String App_Secret="67e6ea957c0616fc94afe7401d670a96";


    private static String Access_Token="";
    //初始化
    static {
        //获取接口调用凭证
        getAccessToken();
    }

    public static void getAccessToken(){
        //获取接口调用凭证
        Map<String,String> map=new HashMap<>();
        map.put("appid",APP_ID);
        map.put("secret",App_Secret);
        map.put("grant_type","client_credential");
        JSONObject jsonObject= HttpClientUtil.doGet("https://api.weixin.qq.com/cgi-bin/token",map);
        //判断是否请求成功
        if(jsonObject.get("access_token")!=null){
            Access_Token= (String) jsonObject.get("access_token");
        }
        System.out.println(jsonObject);
    }

    //登录
    public static Map<String, String> getLogin(String jsCode){

        Map<String,String> map=new HashMap<>();
        map.put("appid",APP_ID);
        map.put("secret",App_Secret);
        map.put("grant_type","authorization_code");
        map.put("js_code",jsCode);
        JSONObject jsonObject= HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session",map);
        //判断请求是否成功
        if(jsonObject.getInteger("errcode")!=null){
            //请求失败
            throw new HttpClientException(jsonObject.getString("errmsg"));
        }
        //请求成功
        Map<String,String> hashMap=new HashMap<>();
        hashMap.put("session_key",jsonObject.getString("session_key"));
        hashMap.put("unionid",jsonObject.getString("unionid"));
        hashMap.put("openid",jsonObject.getString("openid"));
        return hashMap;

    }


}
